package com.example.study.exception;

import com.example.study.common.api.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.sql.SQLSyntaxErrorException;

@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

    //统一请求的Validated验证
    @ExceptionHandler(value = {WebExchangeBindException.class})
    public ResultUtil validExceptionHandler(WebExchangeBindException bindException){
        ObjectError error = bindException.getBindingResult().getAllErrors().get(0);
        log.error("验证错误信息：{}", error.getDefaultMessage());
        return ResultUtil.validateFailed(error.getDefaultMessage());
    }

    //统一请求的Validated验证
    @ExceptionHandler(value = {Exception.class})
    public ResultUtil validExceptionHandler(Exception bindException){
        log.error("验证错误信息：{}", bindException.toString());
        return ResultUtil.validateFailed(bindException.getMessage());
    }

    //统一请求的Validated验证
    @ExceptionHandler(value = {BadSqlGrammarException.class})
    public ResultUtil sqlExceptionHandler(SQLSyntaxErrorException sqlException){
        log.error("执行sql错误信息：{}", sqlException.toString());
        return ResultUtil.validateFailed(sqlException.getMessage());
    }
}
